//
//  DetailViewController.m
//  Custom_Weibo
//
//  Created by LEO on 12/14/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "DetailViewController.h"
#import "CommentTableView.h"
#import "CommentModel.h"
#import "AppDelegate.h"
@interface DetailViewController ()<SinaWeiboRequestDelegate>
@end

@implementation DetailViewController {
    SinaWeiboRequest *_request;
    CommentTableView *_commentList;
    NSMutableArray *_dataArray;
}

#pragma mark - INITIALIZATION_METHODS
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.title = @"Comment Page";
    }
    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.title = @"Comment Page";
    }
    return self;
}

#pragma mark - SYSTEM_METHODS
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //  Download data.
    [self downloadNewData];
    
    //  Create the comment list.
    [self buildCommentList];
    
}

//  Make sure when the view is showed up, disconnect the network.
- (void)viewWillDisappear:(BOOL)animated {
    [_request disconnect];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - TABLE_VIEW
- (void)buildCommentList {
    //  1)Build comment list.
    _commentList = [[CommentTableView alloc] initWithFrame:self.view.bounds
                                                     style:UITableViewStyleGrouped];
    [self.view addSubview:_commentList];
    _commentList.backgroundColor = [UIColor whiteColor];
    
    //  2)Transmit data
    _commentList.weiboModel = self.layoutFrame.weiboModel;
    
    //  3)Pull up to load data.
    __weak DetailViewController *weakSelf = self;
    [_commentList addInfiniteScrollingWithActionHandler:^{
        [weakSelf reloadOldData];
    }];
}

#pragma mark - LOAD_DATA
- (void)downloadNewData {
    NSString *weiboID = _layoutFrame.weiboModel.weiboIdStr;
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:weiboID forKey:@"id"];
    
    SinaWeibo *sinaweibo = [self getSinaWeibo];
    _request = [sinaweibo requestWithURL:kComments
                                  params:params
                              httpMethod:@"GET"
                                delegate:self];
    _request.tag = kNewDataTag;
}

- (void)reloadOldData {
    NSString *weiboID = [_layoutFrame.weiboModel.weiboId stringValue];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:weiboID forKey:@"id"];
    
    CommentModel *commentM = [_dataArray lastObject];
    if (commentM == nil) {
        return;
    }
    
    NSString *lastID = commentM.idstr;
    [params setObject:lastID forKey:@"max_id"];
    
    SinaWeibo *sinaWeibo = [self getSinaWeibo];
    _request = [sinaWeibo requestWithURL:kComments
                                  params:params
                              httpMethod:@"GET"
                                delegate:self];
    _request.tag = kOldDataTag;
}

- (SinaWeibo *)getSinaWeibo {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaWeibo;
}

#pragma mark - REQUEST_FOR_DATA
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    [_commentList.infiniteScrollingView stopAnimating];
    
    NSArray *array = [result objectForKey:@"comments"];
    NSMutableArray *commentArray = [[NSMutableArray alloc] initWithCapacity:array.count];
    for (NSDictionary *dataDic in array) {
        CommentModel *commentModel = [[CommentModel alloc] initWithDataDic:dataDic];
        [commentArray addObject:commentModel];
    }
    
    if (request.tag == kNewDataTag) {
        _dataArray = commentArray;
    }else if (request.tag == kOldDataTag) {
        if (commentArray.count > 1) {
            [commentArray removeObjectAtIndex:0];
            [_dataArray addObjectsFromArray:commentArray];
        }else {
            return;
        }
    }
    
    _commentList.commentListArray = _dataArray;
    
    NSNumber *total = [result objectForKey:@"total_number"];
    NSInteger count = [total integerValue];
    _commentList.commentCount = count;
    [_commentList reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
